package chapter3_v4;

/**
 * @author mazouri
 * @create 2021-10-31 20:56
 */
public class _3 {
    public static void main(String[] args) {
        double[] sites = {0, 2, 5, 7, 12};
        System.out.println(averageShortestDistance(sites));
        System.out.println(minMaxDistance(sites));
    }


    /**
     * 求出邮局的位置，使得各村庄和该邮局之间的平均距离最小。
     *
     * @param sites 村庄的位置
     * @return 邮局的位置
     */
    public static double averageShortestDistance(double[] sites) {
        double res = 0;
        double minLength = Double.MAX_VALUE;
        for (double site : sites) {
            int sum = 0;
            for (double x : sites) {
                sum += (Math.abs(x - site));
            }

            if (minLength > sum) {
                minLength = sum;
                res = site;
            }
        }
        return res;
    }

    /**
     * 用来求出邮局的位置，使得各村庄和该邮局之间的最大距离最小
     *
     * @param sites 村庄的位置
     * @return 邮局的位置
     */
    public static double minMaxDistance(double[] sites) {
        double res = 0;
        double minLength = Double.MAX_VALUE;
        double length = 0;
        int len = sites.length;
        for (double site : sites) {
            length = Math.max(site - sites[0], sites[len - 1] - site);
            if (minLength > length) {
                minLength = length;
                res = site;
            }
        }
        return res;
    }
}
